<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>持仓查看器</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background-color: #0d1117; color: #e6edf3; margin: 0; padding: 15px; }
        .container { max-width: 600px; margin: 0 auto; }
        .header { display: flex; gap: 10px; margin-bottom: 20px; }
        .user-select-btn { flex-grow: 1; padding: 12px; font-size: 16px; background-color: #161b22; border: 1px solid #30363d; color: #848E9C; border-radius: 6px; font-weight: bold; cursor: pointer; transition: all 0.2s ease; }
        .user-select-btn.active { background-color: #FCD535; color: #0d1117; border-color: #F0B90B; }
        .position-card { background-color: #161b22; border: 1px solid #30363d; border-radius: 8px; padding: 15px; margin-bottom: 15px; }
        .card-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #30363d; padding-bottom: 10px; margin-bottom: 10px; }
        .symbol { font-size: 20px; font-weight: bold; color: #FCD535; }
        .pnl { font-size: 20px; font-weight: bold; }
        .price-up { color: #0ECB81; }
        .price-down { color: #F6465D; }
        .details-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; font-size: 14px; }
        .detail-item span { color: #848E9C; }
        .status { text-align: center; color: #848E9C; padding: 20px; }
        .footer { text-align: center; color: #30363d; font-size: 12px; margin-top: 20px; }
        #lastUpdated { font-size: 12px; color: #848E9C; text-align: center; margin-bottom: 15px; height: 16px; }
    </style>
    <script src="https://imgcache.qq.com/qcloud/cloudbase/latest/cloud.js"></script>
</head>
<body>

    <div class="container">
        <div class="header">
            <button class="user-select-btn" data-userid="user_a">用户1持仓</button>
            <button class="user-select-btn" data-userid="user_b">用户2持仓</button>
        </div>
        
        <div id="lastUpdated"></div>
        <div id="positionsContainer">
            <div class="status">请选择要查看的数据</div>
        </div>
        <div class="footer">Powered by Tencent CloudBase</div>
    </div>

    <script>
        // ▼▼▼ 关键步骤：在这里初始化云开发环境 ▼▼▼
        const app = cloudbase.init({
            // 请将这里的 YOUR_ENV_ID 替换为您自己的环境ID
            env: 'cloud1-0ggqg02a362e12e8' 
        });
        // ▲▲▲ 确保这里的ID是您正确的环境ID ▲▲▲

        const db = app.database();
        let unsubscribe; // 用于停止上一个用户的监听

        // 格式化价格函数
        function formatDynamicPrice(value) {
            const price = parseFloat(value);
            if (isNaN(price)) return '-';
            if (price >= 10) return price.toFixed(2);
            if (price >= 1) return price.toFixed(4);
            if (price >= 0.001) return price.toFixed(6);
            if (price >= 0.00001) return price.toFixed(8);
            return price.toString();
        }

        // 渲染持仓列表
        function renderPositions(positions) {
            const container = document.getElementById('positionsContainer');
            if (!positions) {
                container.innerHTML = '<div class="status">暂无持仓数据</div>';
                return;
            }
            const openPositions = positions.filter(p => p.status === 'open');
             if (openPositions.length === 0) {
                container.innerHTML = '<div class="status">暂无持仓数据</div>';
                return;
            }
            let html = '';
            openPositions.forEach(pos => {
                const pnlRate = ((pos.currentPrice - pos.openPrice) / pos.openPrice) * 100;
                const pnlClass = pnlRate >= 0 ? 'price-up' : 'price-down';
                const pnlSign = pnlRate >= 0 ? '+' : '';
                html += `
                    <div class="position-card">
                        <div class="card-header">
                            <span class="symbol">${pos.symbol.replace('USDT','')}</span>
                            <span class="pnl ${pnlClass}">${pnlSign}${pnlRate.toFixed(2)}%</span>
                        </div>
                        <div class="details-grid">
                            <div class="detail-item"><span>开仓价:</span> ${formatDynamicPrice(pos.openPrice)}</div>
                            <div class="detail-item"><span>当前价:</span> ${formatDynamicPrice(pos.currentPrice)}</div>
                        </div>
                    </div>
                `;
            });
            container.innerHTML = html;
        }
        
        // 加载并监听指定用户的数据
        function loadDataForUser(userId) {
            if (!userId) return;

            if (unsubscribe) {
                unsubscribe(); // 停止监听上一个用户的数据
            }

            const container = document.getElementById('positionsContainer');
            container.innerHTML = '<div class="status">正在连接...</div>';
            document.getElementById('lastUpdated').textContent = '';
            
            // 实时监听云端数据
            unsubscribe = db.collection('positions').doc(userId)
                .watch({
                    onChange: (snapshot) => {
                        console.log('收到数据更新:', snapshot);
                        if (snapshot.docs.length > 0) {
                            const data = snapshot.docs[0];
                            const positions = data.positions || [];
                            const lastUpdated = data._updateTime ? new Date(data._updateTime).toLocaleString('zh-CN') : 'N/A';
                            
                            document.getElementById('lastUpdated').textContent = `数据更新于: ${lastUpdated}`;
                            renderPositions(positions);
                        } else {
                            container.innerHTML = '<div class="status">未找到该用户ID的数据</div>';
                            document.getElementById('lastUpdated').textContent = '连接失败';
                        }
                    },
                    onError: (error) => {
                        console.error("监听失败:", error);
                        container.innerHTML = `<div class="status" style="color:#F6465D;">连接错误，请检查网络</div>`;
                    }
                });
            
            localStorage.setItem('lastSelectedUserId', userId);
        }

        // 页面加载和按钮点击事件
        document.addEventListener('DOMContentLoaded', () => {
            const userButtons = document.querySelectorAll('.user-select-btn');
            
            userButtons.forEach(button => {
                button.addEventListener('click', () => {
                    userButtons.forEach(btn => btn.classList.remove('active'));
                    button.classList.add('active');
                    
                    const userId = button.getAttribute('data-userid');
                    loadDataForUser(userId);
                });
            });

            // 自动加载上次选择的用户
            const lastUserId = localStorage.getItem('lastSelectedUserId');
            if (lastUserId) {
                const lastButton = document.querySelector(`.user-select-btn[data-userid="${lastUserId}"]`);
                if (lastButton) {
                    lastButton.click();
                }
            }
        });
    </script>

</body>
</html>